package org.zcl.stategy.entity;

import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Package org.zcl.stategy.entity
 * @PROJECT_NAME: question
 * @DESCRIPTION:
 * @USER: zhuchenglin
 * @DATE: 2022/6/22 9:56
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Pool {
    private String name;
    private int value;

    /**
     * @Description 使用Java8的流进行处理，将name相同的对象进行合并，将value属性求和
     * @Title merge
     * @Param [list]
     * @Return java.util.List<Pool>
     * @Author Louis
     */
    public static List<Pool> merge(List<Pool> list) {
        Map<String, Pool> map = new HashMap<>();
        list.forEach(pool -> {
            Pool last = map.get(pool.getName());
            if(null != last){
                pool.setValue(pool.getValue() + last.getValue());
            }
            map.put(pool.getName(), pool);
        });
        return new ArrayList<>(map.values());
    }

    /**
     * @Description 使用Java8的流进行处理，将name相同的对象进行合并，将value属性求和
     * @Title merge
     * @Param [list]
     * @Return java.util.List<Pool>
     * @Author Louis
     */
    public static List<Pool> merge2(List<Pool> list) {
        return new ArrayList<>(list.stream()
                // 表示name为key，接着如果有重复的，那么从Pool对象o1与o2中筛选出一个，这里选择o1，
                // 并把name重复，需要将value与o1进行合并的o2, 赋值给o1，最后返回o1
                .collect(Collectors.toMap(Pool::getName, a -> a, (o1, o2) -> {
                    o1.setValue(o1.getValue() + o2.getValue());
                    return o1;
                })).values());
    }

    public static void main(String[] args) {
        List<Pool> list = new ArrayList<Pool>(){
            private static final long serialVersionUID = 4124186171575197502L;

            {
                add(new Pool("A", 1));
                add(new Pool("A", 2));
                add(new Pool("A", 3));
                add(new Pool("B", 4));
                add(new Pool("B", 5));
            }
        };

        List<Pool> result = merge(list);
        System.err.println(JSONObject.toJSONString(result));
    }
}